package mo.offer_special;

import java.util.*;

@SuppressWarnings("Duplicates")
/**
 * 插入、删除和随机访问都是O(1)的数据结构
 */
public class L030 {

    private Map<Integer, Integer> value2index;
    private List<Integer> nums;
    private Random random;


    /** Initialize your data structure here. */
    public L030() {
        value2index = new HashMap<>();
        nums = new ArrayList<>();
        random = new Random();
    }

    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    public boolean insert(int val) {
        if (value2index.containsKey(val)) {
            return false;
        }
        int size = nums.size();
        value2index.put(val, size);
        nums.add(val);
        return true;
    }

    /** Removes a value from the set. Returns true if the set contained the specified element. */
    public boolean remove(int val) {
        Integer index = value2index.get(val);
        if (index == null) {
            return false;
        }

        int last = nums.get(nums.size()-1);
        nums.set(index, last);
        nums.remove(nums.size()-1);
        value2index.put(last, index);
        value2index.remove(val);
        return true;
    }

    /** Get a random element from the set. */
    public int getRandom() {
        int size = nums.size();
        int index = random.nextInt(size);
        return nums.get(index);
    }

}
